package cn.tedu._03vehicle.controller;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.mapper.NoticeMapper;
import cn.tedu._03vehicle.pojo.vo.NoticeListVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 通知管理控制器
 */
@Slf4j
@RestController
@Tag(name = "公告管理模块")
@RequestMapping("/v1/notice/")
public class NoticeController {
    @Autowired
    private NoticeMapper noticeMapper;

    //自动装配RedisTemplate
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    /**
     * 1.首页公告列表
     */
    @GetMapping("list")
    @Operation(summary = "首页公告列表")
    @ApiOperationSupport(order = 10)
    public JsonResult list(){
        /*
            * 数据类型选择: 字符串String
            * key-value设计:
               key设计: notice_index
               value设计: List<NoticeListVO> --> '[{},{},{},{},...]'
            * 程序思路:
             1.确认缓存中是否存在首页数据[Redis执行GET命令];
             2.缓存中不存在:
               2.1 从MySQL中查询数据[noticeMapper.list()];
               2.2 将数据保存到缓存中[Redis执行SET命令],缓存时间为30秒;
             3.缓存中存在:直接返回;
         */
        ValueOperations<String, Serializable> ops = redisTemplate.opsForValue();
        Serializable noticeIndex = ops.get("notice_index");
        if (noticeIndex == null){ //缓存中不存在
            log.debug("数据来自于MySQL数据库...");
            List<NoticeListVO> noticeListVOS = noticeMapper.list();
            // 将数据保存到缓存中
            ops.set("notice_index", (Serializable) noticeListVOS, 30, TimeUnit.SECONDS);
            return JsonResult.ok(noticeListVOS);
        }

        log.debug("数据来源于Redis缓存...");
        return JsonResult.ok(noticeIndex);
    }
}












